package com.spring.api.web.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.oa.api.web.dao.OaMapper;
import com.spera.genutil.BuzWechatContent;
import com.spera.genutil.HttpClientNUtils;
import com.spera.genutil.WechatUtil;
import com.spring.api.web.dao.BuzWechatMapper;
import com.spring.api.web.dao.WxNoticeConfigMapper;
import com.spring.api.web.dao.WxNoticeLogMapper;
import com.spring.api.web.model.WxNoticeConfig;
import com.spring.api.web.model.WxNoticeLog;
import com.spring.api.web.service.BuzWechatService;
import com.spring.security.core.util.ApplicationUtils;
import com.spring.security.web.model.BaseResult;

@Service
public class BuzWechatServiceImpl implements BuzWechatService{

	@Resource private OaMapper oaMapper;
	
	@Resource private BuzWechatMapper buzWechatMapper;
	
	@Resource private WxNoticeConfigMapper wxNoticeConfigMapper;
	
	@Resource private WxNoticeLogMapper wxNoticeLogMapper;
	
	@Override
	public BaseResult notice(){
		BaseResult ret = new BaseResult();
		try{
			Map<String, Object> oaParm = new HashMap<String,Object>();
			oaParm.put("wx_remind", "0");//第一次
			List<Map<String, Object>> lm = oaMapper.queryMeettingInfos(oaParm);
			if(lm!=null&&lm.size()>0){
				Map<String, String> map = new HashMap<String, String>();
		        map.put("corpid", BuzWechatContent.CORPID);
		        map.put("corpsecret", BuzWechatContent.CORPSECRET);
		        HttpClient client = HttpClientNUtils.getConnection();
		        HttpUriRequest get = HttpClientNUtils.getRequestMethod(map, "https://qyapi.weixin.qq.com/cgi-bin/gettoken", "get");
		        HttpResponse response = client.execute(get);
		 
		        String content = "";
		        if (response.getStatusLine().getStatusCode() == 200) {
		            HttpEntity entity = response.getEntity();
		            content = EntityUtils.toString(entity, "utf-8");
	//	            System.out.println(content);
		        } else {
		        	ret.setMsg("请求失败");
		        	ret.setStatus("0");
		        	return ret;
		        }
				
				Map<String, Object> mapParm = JSON.parseObject(content, new TypeReference<Map<String, Object>>(){});
				for(Map<String, Object> m:lm){
					/*BaseResult retOne = */sendMeetingNotice(mapParm,m,"1");
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			ret.setMsg("请求失败");
        	ret.setStatus("0");
		}
		
		return ret;
	}
	
	
	
	@Override
	public BaseResult noticeTwice(){
		BaseResult ret = new BaseResult();
		try{
			Map<String, Object> oaParm = new HashMap<String,Object>();
			oaParm.put("wx_remind", "1");//第二次
			List<Map<String, Object>> lm = oaMapper.queryMeettingInfos(oaParm);
			if(lm!=null&&lm.size()>0){
				Map<String, String> map = new HashMap<String, String>();
		        map.put("corpid", BuzWechatContent.CORPID);
		        map.put("corpsecret", BuzWechatContent.CORPSECRET);
		        HttpClient client = HttpClientNUtils.getConnection();
		        HttpUriRequest get = HttpClientNUtils.getRequestMethod(map, "https://qyapi.weixin.qq.com/cgi-bin/gettoken", "get");
		        HttpResponse response = client.execute(get);
		 
		        String content = "";
		        if (response.getStatusLine().getStatusCode() == 200) {
		            HttpEntity entity = response.getEntity();
		            content = EntityUtils.toString(entity, "utf-8");
	//	            System.out.println(content);
		        } else {
		        	ret.setMsg("请求失败");
		        	ret.setStatus("0");
		        	return ret;
		        }
				
				Map<String, Object> mapParm = JSON.parseObject(content, new TypeReference<Map<String, Object>>(){});
				for(Map<String, Object> m:lm){
					/*BaseResult retOne = */sendMeetingNotice(mapParm,m,"2");
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			ret.setMsg("请求失败");
        	ret.setStatus("0");
		}
		
		return ret;
	}
	
	/**
	 * 会议信息推送
	 * @param mapParm
	 * @param mapPer
	 * @param type
	 * @return
	 */
	private BaseResult sendMeetingNotice(Map<String, Object> mapParm,Map<String, Object> mapPer,String type){
		BaseResult ret = new BaseResult("0","发送失败");
		String userId = ApplicationUtils.Object2String(mapPer.get("userid"));
		String userName = ApplicationUtils.Object2String(mapPer.get("username"));
		if(ApplicationUtils.isNotNull(mapParm.get("access_token"))&&ApplicationUtils.isNotNull(userId)){
			String access_token = (String)mapParm.get("access_token");
			String nUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+access_token;
			StringBuffer sb = new StringBuffer();
			String wxcontent = "请准时于"+ApplicationUtils.Object2String(mapPer.get("beginTime"))+"到"+
					ApplicationUtils.Object2String(mapPer.get("room"))+"参加"+ApplicationUtils.Object2String(mapPer.get("content"));
			sb.append("{\"touser\":\""+ApplicationUtils.Object2String(userId).replaceAll(",", "|")+"\",");
			sb.append("\"msgtype\":\"text\",");
			sb.append("\"agentid\":\"4\",");
			sb.append("\"text\":{\"content\":\""+wxcontent+"\"},");
			sb.append("\"safe\":\"0\"}");
			String content = HttpClientNUtils.httpPost(nUrl, sb.toString());
			mapParm = JSON.parseObject(content, new TypeReference<Map<String, Object>>(){});
			if("0".equals(ApplicationUtils.Object2String(mapParm.get("errcode")))){
				//更新发送标记
				mapPer.put("wx_remind", type);
				oaMapper.updateMeettingInfos(mapPer);//更新标记
				//记录日志
				WxNoticeLog log = new WxNoticeLog();
				log.initInfo();
				log.setId(ApplicationUtils.randomUUID()).setUserid(userId).setUsername(userName).setContent(wxcontent)
					.setSendtime(new Date()).setWxNoticeType(1).setNote("会提通知提醒正常推送");
				wxNoticeLogMapper.insert(log);
				ret.setMsg("发送成功");
	        	ret.setStatus("1");
			}
		}
		return ret;
	}


	/**
	 * 检测纪念日并推送微信企业号  提前一个月
	 */
	@Override
	public void specialdayNotice30() {
		System.out.println("xxx---->----specialdayNotice30-----");
		try{
			//获取最近将要到来的纪念日
			List<Map<String, Object>> retList = buzWechatMapper.checkCusSpecialday30();
			if(retList!=null&&retList.size()>0){
				Map<String, String> map = new HashMap<String, String>();
		        map.put("corpid", BuzWechatContent.CORPID);
		        map.put("corpsecret", BuzWechatContent.CORPSECRET);
		        HttpClient client = HttpClientNUtils.getConnection();
		        HttpUriRequest get = HttpClientNUtils.getRequestMethod(map, "https://qyapi.weixin.qq.com/cgi-bin/gettoken", "get");
		        HttpResponse response = client.execute(get);
		 
		        String content = "";
		        if (response.getStatusLine().getStatusCode() == 200) {
		            HttpEntity entity = response.getEntity();
		            content = EntityUtils.toString(entity, "utf-8");
		        } else {
		        }
				
				Map<String, Object> mapParm = JSON.parseObject(content, new TypeReference<Map<String, Object>>(){});
				for(Map<String, Object> m:retList){
					/*BaseResult retOne = */sendSpecialdayNotice(mapParm,m,"1");
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 检测纪念日并推送微信企业号   提前半个月
	 */
	@Override
	public void specialdayNotice15() {
		System.out.println("xxx---->----specialdayNotice15-----");
		try{
			//获取最近将要到来的纪念日
			List<Map<String, Object>> retList = buzWechatMapper.checkCusSpecialday15();
			if(retList!=null&&retList.size()>0){
				Map<String, String> map = new HashMap<String, String>();
		        map.put("corpid", BuzWechatContent.CORPID);
		        map.put("corpsecret", BuzWechatContent.CORPSECRET);
		        HttpClient client = HttpClientNUtils.getConnection();
		        HttpUriRequest get = HttpClientNUtils.getRequestMethod(map, "https://qyapi.weixin.qq.com/cgi-bin/gettoken", "get");
		        HttpResponse response = client.execute(get);
		 
		        String content = "";
		        if (response.getStatusLine().getStatusCode() == 200) {
		            HttpEntity entity = response.getEntity();
		            content = EntityUtils.toString(entity, "utf-8");
		        } else {
		        }
				
				Map<String, Object> mapParm = JSON.parseObject(content, new TypeReference<Map<String, Object>>(){});
				for(Map<String, Object> m:retList){
					/*BaseResult retOne = */sendSpecialdayNotice(mapParm,m,"2");
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 纪念日信息推送
	 * @param mapParm 微信token相关参数
	 * @param mapPer 内容
	 * @param type 是否已推送标记
	 * @return
	 */
	private BaseResult sendSpecialdayNotice(Map<String, Object> mapParm,Map<String, Object> mapPer,String type){
		BaseResult ret = new BaseResult("0","发送失败");
		String userId = ApplicationUtils.Object2String(mapPer.get("userid"));
		String userName = ApplicationUtils.Object2String(mapPer.get("username"));
		if(ApplicationUtils.isNotNull(mapParm.get("access_token"))&&ApplicationUtils.isNotNull(userId)){
			String access_token = (String)mapParm.get("access_token");
			String nUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+access_token;
			StringBuffer sb = new StringBuffer();
			String wxcontent = ApplicationUtils.Object2String(mapPer.get("cusName"))+"客户的"+ApplicationUtils.Object2String(mapPer.get("dayName"))
			+"纪念日将在"+ApplicationUtils.Object2String(mapPer.get("dayTime"))+"时间到来，请安排好与客户的沟通工作";
			sb.append("{\"touser\":\""+ApplicationUtils.Object2String(userId).replaceAll(",", "|")+"\",");
			sb.append("\"msgtype\":\"text\",");
			sb.append("\"agentid\":\"4\",");
			sb.append("\"text\":{\"content\":\""+wxcontent+"\"},");
			sb.append("\"safe\":\"0\"}");
			String content = HttpClientNUtils.httpPost(nUrl, sb.toString());
			mapParm = JSON.parseObject(content, new TypeReference<Map<String, Object>>(){});
			if("0".equals(ApplicationUtils.Object2String(mapParm.get("errcode")))){
				//更新标记
				mapPer.put("type", type);
				buzWechatMapper.updateSpecialdaySendStatus(mapPer);//更新标记
				//记录日志
				WxNoticeLog log = new WxNoticeLog();
				log.initInfo();
				log.setId(ApplicationUtils.randomUUID()).setUserid(userId).setUsername(userName).setContent(wxcontent)
					.setSendtime(new Date()).setWxNoticeType(3).setNote("纪念日提醒正常推送");
				wxNoticeLogMapper.insert(log);
				ret.setMsg("发送成功");
	        	ret.setStatus("1");
			}
		}
		return ret;
	}



	@Override
	public BaseResult cooTaskTransNotice() {
		BaseResult ret = new BaseResult();
		try{
			Map<String, Object> oaParm = new HashMap<String,Object>();
			oaParm.put("wx_remind", "0");//第一次
			List<Map<String, Object>> lm = buzWechatMapper.queryCooTaskTrans(oaParm);
			if(lm!=null&&lm.size()>0){
				for(Map<String, Object> m:lm){
					sendCooTaskTransNotice(WechatUtil.getAccessToken(),m,"1");
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			ret.setMsg("请求失败");
        	ret.setStatus("0");
		}
		return ret;
	}
	
	@SuppressWarnings("unchecked")
	private BaseResult sendCooTaskTransNotice(String access_token,Map<String, Object> mapPer,String type){
		BaseResult ret = new BaseResult("0","发送失败");
		String userId = ApplicationUtils.Object2String(mapPer.get("userid"));
		String userName = ApplicationUtils.Object2String(mapPer.get("username"));
		if(!"".equals(access_token)&&ApplicationUtils.isNotNull(userId)){
			String content = "您有新的协同任务需要处理，请登录OA进行查看";
			ret = WechatUtil.sendQyhNotice(access_token, ApplicationUtils.Object2String(userId), content);
			Map<String, Object> mapParm = (Map<String, Object>)ret.getDataset();
			if("0".equals(ApplicationUtils.Object2String(mapParm.get("errcode")))){
				//更新标记
				mapPer.put("wx_remind", type);
				buzWechatMapper.updateCooTaskTrans(mapPer);//更新标记
				//记录日志
				WxNoticeLog log = new WxNoticeLog();
				log.initInfo();
				log.setId(ApplicationUtils.randomUUID()).setUserid(userId).setUsername(userName).setContent(content)
					.setSendtime(new Date()).setWxNoticeType(2).setNote("协同任务提醒正常推送");
				wxNoticeLogMapper.insert(log);
				ret.setMsg("发送成功");
	        	ret.setStatus("1");
			}
		}
		return ret;
	}


	//客户拜访通知
	@Override
	public void crmVisitRecordNotice() {
		try{
			Map<String, Object> oaParm = new HashMap<String,Object>();
			oaParm.put("wx_remind", "0");//第一次
			List<Map<String, Object>> lm = buzWechatMapper.queryCrmVisitRecord(oaParm);
			if(lm!=null&&lm.size()>0){
				for(Map<String, Object> m:lm){
					sendCrmVisitRecordNotice(WechatUtil.getAccessToken(),m,"1");
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings("unchecked")
	private BaseResult sendCrmVisitRecordNotice(String access_token,Map<String, Object> mapPer,String type){
		BaseResult ret = new BaseResult("0","发送失败");
		String userId = ApplicationUtils.Object2String(mapPer.get("userid"));
		String userName = ApplicationUtils.Object2String(mapPer.get("username"));
		if(!"".equals(access_token)&&ApplicationUtils.isNotNull(userId)){
			String content = "您有新的拜访通知，请登录OA进行查看";
			ret = WechatUtil.sendQyhNotice(access_token, ApplicationUtils.Object2String(userId), content);
			Map<String, Object> mapParm = (Map<String, Object>)ret.getDataset();
			if("0".equals(ApplicationUtils.Object2String(mapParm.get("errcode")))){
				//更新标记
				mapPer.put("isSend", type);
				buzWechatMapper.updateCrmVisitRecord(mapPer);
				//记录日志
				WxNoticeLog log = new WxNoticeLog();
				log.initInfo();
				log.setId(ApplicationUtils.randomUUID()).setUserid(userId).setUsername(userName).setContent(content)
					.setSendtime(new Date()).setWxNoticeType(4).setNote("客户拜访提醒正常推送");
				wxNoticeLogMapper.insert(log);
				ret.setMsg("发送成功");
	        	ret.setStatus("1");
			}
		}
		return ret;
	}

	//公共发送接口
	@Override
	public void publicNotice() {
		try{
			List<WxNoticeConfig> lm = 	wxNoticeConfigMapper.selectByParm(null);
			System.out.println("-------->publicNotice");
			if(lm!=null&&lm.size()>0){
				for(WxNoticeConfig m:lm){
					BaseResult ret = sendPublicNotice(WechatUtil.getAccessToken(),m);
					System.out.println("--->"+ret.getMsg());
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings("unchecked")
	private BaseResult sendPublicNotice(String access_token,WxNoticeConfig mapPer){
		BaseResult ret = new BaseResult("0","发送失败");
		if(StringUtils.isBlank(mapPer.getContent())){
			ret.setMsg("内容不可为空");
        	ret.setStatus("0");
        	return ret;
		}
		
		if(StringUtils.isBlank(mapPer.getNoticeSql())){
			ret.setMsg("推送脚本不可为空");
        	ret.setStatus("0");
        	return ret;
		}
		
		if(StringUtils.isBlank(mapPer.getTableNameZn())){
			ret.setMsg("推送表英文名不可为空");
        	ret.setStatus("0");
        	return ret;
		}
		
		if(StringUtils.isBlank(mapPer.getNoticeColumn())){
			ret.setMsg("推送状态字段不可为空");
        	ret.setStatus("0");
        	return ret;
		}
		
		if(StringUtils.isBlank(mapPer.getNoticeAfterStatus())){
			ret.setMsg("推送后状态不可为空");
        	ret.setStatus("0");
        	return ret;
		}
		
		if(StringUtils.isBlank(access_token)){
			ret.setMsg("accesstoken不可为空");
        	ret.setStatus("0");
        	return ret;
		}
		
		//检测脚本
		if(mapPer.getNoticeSql().toLowerCase().indexOf("select")==-1||
				mapPer.getNoticeSql().toLowerCase().indexOf("from")==-1){
			ret.setMsg("脚本有误，请检查");
        	ret.setStatus("0");
        	return ret;
		}
		if(mapPer.getNoticeSql().toLowerCase().indexOf("id")==-1){//必须存在推送表主键编号字段
			ret.setMsg("推送表主键编号不可为空");
        	ret.setStatus("0");
        	return ret;
		}
		if(mapPer.getNoticeSql().toLowerCase().indexOf("recname")==-1){//必须存在接收人字段
			ret.setMsg("接收人不可为空");
        	ret.setStatus("0");
        	return ret;
		}
		if(mapPer.getNoticeSql().toLowerCase().indexOf("receiver")==-1){//必须存在接收人编号字段
			ret.setMsg("接收人编号不可为空");
        	ret.setStatus("0");
        	return ret;
		}
//		if(mapPer.getNoticeSql().toLowerCase().indexOf("content")==-1){//必须存在内容字段
//			ret.setMsg("内容不可为空");
//        	ret.setStatus("0");
//        	return ret;
//		}
		
		//执行sql
		List<Map<String,Object>> retL;
		try{
			retL = buzWechatMapper.queryNoticeListBySql(mapPer.getNoticeSql().toLowerCase());
		}catch(Exception e){
			e.printStackTrace();
			ret.setMsg("脚本执行有误");
        	ret.setStatus("0");
        	return ret;
		}
		if(retL==null||retL.size()==0){
			return ret.setStatus("0").setMsg("无可推送内容");
		}
		Map<String, Object> mapParm = null;
		Map<String, Object> tableParm = new HashMap<String, Object>();
		tableParm.put("tablename", mapPer.getTableNameZn());
		tableParm.put("status", mapPer.getNoticeColumn());
		tableParm.put("status_value", mapPer.getNoticeAfterStatus());
		for(Map<String,Object> one:retL){
			String content = mapPer.getContent();
			//替换脚本中的字段到内容变量中
//			Map<String, Object> map = new HashMap<String, Object>();  
	        for (Map.Entry<String, Object> entry : one.entrySet()) { 
	        	content = content.toLowerCase().replaceAll("@"+entry.getKey()+"", ApplicationUtils.Object2String(entry.getValue()));
	        }
			
			ret = WechatUtil.sendQyhNotice(access_token, ApplicationUtils.Object2String(one.get("receiver")), content);
			mapParm = (Map<String, Object>)ret.getDataset();
			if("0".equals(ApplicationUtils.Object2String(mapParm.get("errcode")))){
				//更新标记
				tableParm.put("id", one.get("id"));
				buzWechatMapper.updateNoticeStatus(tableParm);
				
				//记录日志
				WxNoticeLog log = new WxNoticeLog();
				log.initInfo();
				log.setId(ApplicationUtils.randomUUID()).setUserid(ApplicationUtils.Object2String(one.get("receiver")))
					.setUsername(ApplicationUtils.Object2String(one.get("recname"))).setContent(content)
					.setSendtime(new Date()).setWxNoticeType(4).setNote("其他提醒正常推送");
				wxNoticeLogMapper.insert(log);
				ret.setMsg("发送成功");
	        	ret.setStatus("1");
			}
		}
		return ret;
	}


//	//根据日至再次发送接口
	@SuppressWarnings("unchecked")
	@Override
	public BaseResult sendNotice(String ids) {
		BaseResult ret = new BaseResult("0","发送失败");
		if(StringUtils.isBlank(ids)){
			ret.setMsg("用户编号不可为空");
        	ret.setStatus("0");
        	return ret;
		}
	    String[] strArr = ids.split(",");
	    String whereIds = "";
	    for(String strId:strArr){
	    	whereIds += "'"+strId+"',";
	    }
	    whereIds = whereIds.substring(0,whereIds.length()-1);
		List<WxNoticeLog> wxLogList =  wxNoticeLogMapper.selectByIds(whereIds);
		int i=0;
		String errnames = "";
		for(WxNoticeLog log:wxLogList){
			if(ApplicationUtils.isNotNull(log.getUserid())){
				ret = WechatUtil.sendQyhNotice(WechatUtil.getAccessToken(), ApplicationUtils.Object2String(log.getUserid()), log.getContent());
				Map<String, Object> mapParm = (Map<String, Object>)ret.getDataset();
				if(!"0".equals(ApplicationUtils.Object2String(mapParm.get("errcode")))){
					//重新记录日志
					WxNoticeLog nlog = new WxNoticeLog();
					nlog.initInfo();
					nlog.setId(ApplicationUtils.randomUUID()).setUserid(log.getUserid()).setUsername(log.getUsername())
						.setContent(log.getContent()).setSendtime(new Date())
						.setWxNoticeType(log.getWxNoticeType()).setNote("二次手工推送");
					wxNoticeLogMapper.insert(nlog);
					i++;
				}else{
					errnames+=log.getUsername()+",";
				}
			}else{
				errnames+=log.getUsername()+",";
			}
		}
		if(i==0){
			ret.setMsg("发送成功");
	    	ret.setStatus("1");
		}else{
			errnames = errnames.substring(0,errnames.length()-1);
			ret.setMsg(errnames+" 推送失败");
	    	ret.setStatus("0");
		}
		return ret;
	}
	
}
